﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Disposables;
using System.Linq.Expressions;
using System.Windows;
using System.Windows.Data;
using SoftSource.Common;
using SoftSource.Timecard.ViewModelInterfaces;
using SoftSource.Timecard.Web.Data;

namespace SoftSource.Timecard.ViewModels
{
    public sealed class UserListViewModel : IUserListViewModel
    {
        #region Fields
        private CompositeDisposable compositeDisposable;
        private IEnumerable<UserSummary> userSummaries;
        #endregion Fields

        public UserListViewModel()
        {
            this.compositeDisposable = new CompositeDisposable();
        }

        #region IUserListViewModelConsume Members

        private PagedCollectionView users;
        public PagedCollectionView Users
        {
            get { return this.users; }
            set
            {
                this.users = value;
                this.users.SortDescriptions.Add(new SortDescription(
                    ObjectReflection.GetPropertyName<UserSummary>(u => u.FullName),
                    ListSortDirection.Ascending));
                this.users.MoveCurrentToFirst();
                this.PropertyChanged.Notify(() => this.Users);
            }
        }

        public Func<int, Action, UIElement> CreateUserEditor { get; set; }
        public Func<Action, UIElement> CreateNewUserEditor { get; set; }

        public IObservable<Unit> Load { get; set; }

        #endregion

        #region IUserListViewModelService Members

        public IEnumerable<UserSummary> UserSummaries
        {
            get { return this.userSummaries; }
            set
            {
                this.userSummaries = value;
                this.Users = new PagedCollectionView(this.userSummaries);
            }
        }

        #endregion

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        #endregion

        #region IDisposable Members

        public void Dispose()
        {
            this.compositeDisposable.Dispose();
            GC.SuppressFinalize(this);
        }

        #endregion

        ~UserListViewModel()
        {
            this.Dispose();
        }
    }
}
